#!/usr/bin/perl
#disk_format.cgi
use File::Basename;

require './diskman-lib.pl';

&ReadParse();

my ($disk,$index,$err_msg,$unit,$begin,$name,$sysvpart,$markpart);

$sysvpart=$hwinfo{'sysvpart'}? $hwinfo{'sysvpart'}: 1; 
$markpart=$hwinfo{'markpart'}? $hwinfo{'markpart'}: 6;

if(!$in{'disk'}) {
	$err_msg=$text{'err_cgiparam'};
	goto ERROR_OUT;
}

if($in{'disk'} =~ /disk(\d+)/ ) {
	$index=$1;
} else {
	$err_msg=$text{'err_cgiparam'};
	goto ERROR_OUT;
}

@dinfo=&get_diskindex();

$disk=&diskname2rdev(\@dinfo,$in{'disk'});

if(!$disk) {
	$err_msg=$text{'err_cgiparam'};
	goto ERROR_OUT;
}

$msize=`sfdisk -s $disk`;
if($?){
	$err_msg=$text{'err_dfmt_get_disksize'};
	goto ERROR_OUT;
}
if($msize < $hwinfo{'disksize'} ){
	$err_msg=$text{'err_dfmt_err_disksize'};
	goto ERROR_OUT;
}

#if no sysvol and raid,mkraiid by one disk
$volname='/sysvol';
$mddev='/dev/md0';
$mksysvol=mksysvol();

if($mksysvol) {
	$out=`sfdisk -uM $disk 2>/dev/null <<!
,256,fd
,256,fd
,256,fd
,,5
,256,fd
,256,fd
,256,fd
,,83
!`;
	if($?){
		if($out =~ /This disk is currently in use/) {
			$err_msg=$text{'err_dfmt_device_busy'};
		} else {
			$err_msg=$text{'err_dfmt_run_sfdisk'}.$out;
		}
		goto ERROR_OUT;
	}
	my @rdevs=($disk .1,$disk .2,$disk .3,$disk .5,$disk .6,$disk .7);
	$rc = create_volume(1, \@rdevs, $volname, $mddev, undef);
	if ($rc) {
		$err_msg = $text{'err_crtvol'};
		goto ERROR_OUT;
	}
	system("raidstop $mddev 2>/dev/null");
}

$usize=int($msize/1024)-640;

$out=`sfdisk -uM $disk 2>/dev/null <<!
,256,fd
,256,82
,,5
0
,$usize,fa
,,83
!`;

if($?){
	if($out =~ /This disk is currently in use/) {
		$err_msg=$text{'err_dfmt_device_busy'};
	} else {
		$err_msg=$text{'err_dfmt_run_sfdisk'};
	}
	goto ERROR_OUT;
}

$out=`echo Esteem EzStor1.0 | dd of=$disk$markpart bs=16 count=1 2>/dev/null `;
if($?){
	$err_msg=$text{'err_dfmt_make_label'};
	goto ERROR_OUT;
}
if($mksysvol) {
	`shutdown -r now`;
	&redirect("");
}

$out=`raidhotadd /dev/md0 $disk$sysvpart 2>/dev/null `;
if($?){
	$err_msg=$text{'err_dfmt_run_raidhotadd'};
	goto ERROR_OUT;
}

open(DI,$config{'diskinfo'});
@out=<DI>;
close(DI);
if(!@out) {
	$err_msg=$text{'err_dfmt_read_diskinfo'};
	goto ERROR_OUT;
}

$out[$index-1] =~ s/unknown/well/;

open(DI,"> $config{'diskinfo'}");
print DI @out;
close(DI);

redirect("index.cgi");

ERROR_OUT:
&error_setup($text{'diskfmt_err_title'});
&error($err_msg);
